package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: CustomerServiceImpl
 * Package: com.atguigu.jxc.service.impl
 * Description:
 *
 * @Author 梅超凡
 * @Create 2025/2/21 15:49
 * @Version 1.0
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;


    /**
     * 客户管理
     * @param page 页码
     * @param rows 每页显示条数
     * @param customerName 客户姓名
     * @return 返回结果
     */
    @Override
    public Map<String, Object> customerList(Integer page, Integer rows, String customerName) {
        Map<String, Object> result = new HashMap<>();

        page = (page - 1) * rows;

        List<Customer> customers = customerDao.customerList(page, rows, customerName);
        int total = customers.size();
        result.put("rows", customers);
        result.put("total", total);
        return result;
    }

    /**
     * 添加或修改客户
     * @param customer 客户信息
     * @return 返回结果
     */
    @Override
    public ServiceVO<Object> saveOrUpdate(Customer customer) {

        //获取供应商ID
        Integer customerId = customer.getCustomerId();
        //定义结果变量
        int i = 0;
        //ID为空，插入供应商信息
        if (customerId == null) {
            i = customerDao.saveCustomer(customer);
        }else {
            //否则根据ID更新供应商信息
            i = customerDao.updateById(customer);
        }
        if (i > 0){
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS,i);
        }
        return new ServiceVO<>(ErrorCode.UPDATE_OR_ADD_ERROR_CODE, ErrorCode.UPDATE_OR_ADD_ERROR_MESS,i);
    }

    @Override
    public ServiceVO<Object> deleteById(String ids) {
        String[] splitIds = ids.split(",");
        System.out.println("本次删除"+splitIds.length + "条数据");
        //生成Id集合
        List<Integer> listIds = new ArrayList<>();
        for (String id : splitIds) {
            listIds.add(Integer.parseInt(id));
        }
        int count = customerDao.deleteCustomerById(listIds);
        if (count > 0){
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS,count);
        }
        return new ServiceVO<>(ErrorCode.GOODS_TYPE_ERROR_CODE, ErrorCode.GOODS_TYPE_ERROR_MESS,count);
    }
}
